#-*- coding: UTF-8 -*-

import math, sys, timeit
import pp

def is_prime(n):
    """返回 n 是否是素数"""
    if not isinstance(n, int):
        raise TypeError("argument passed to is_prime is not of 'int' type")
    if n < 2:
        return False
    if n == 2:
        return True
    max = int(math.ceil(math.sqrt(n)))
    i = 2
    while i <= max:
        if n % i == 0:
            return False
        i += 1
    return True

def sum_primes(n):
    """计算从 2-n 之间的所有素数之和"""
    return sum([x for x in xrange(2, n) if is_prime(x)])

if __name__ == "__main__":
    inputs = (100000, 100100, 100200, 100300, 100400, 100500, 100600, 100700)

    def test_single():
        for input in inputs:
            print sum_primes(input)
    
    # tuple of all parallel python servers to connect with
    def test_pp():
        # Creates jobserver with ncpus workers
        job_server = pp.Server()
        print "pp 可以用的工作核心线程数", job_server.get_ncpus(), "workers"
        jobs = [(input, job_server.submit(sum_primes, (input, ), (is_prime,), ("math",))) for input in inputs]
        for input, job in jobs:
            print "Sum of primes below", input, "is", job()
        job_server.print_stats()
    
    t1 = timeit.Timer("test_single()", setup="from __main__ import test_single")
    t2 = timeit.Timer("test_pp()", setup="from __main__ import test_pp")

    print '单线程执行，总耗时', t1.timeit(number=1)
    print "多线程下执行耗时: ", t2.timeit(number=1)
